package com.enbatis.mybatisplugs.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.enbatis.mybatisplugs.shiro.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();

        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //添加Shiro内置管理器

        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         * 常用的过滤器
         *      anon
         *      authc
         *      user
         *      perms
         *      role
         */


        Map<String,String> filterMap=new LinkedHashMap<>();
        filterMap.put("/v1/login/test","anon");
        filterMap.put("/v1/login/login","anon");

        filterMap.put("/v1/login/add","perms[user:add]");
        filterMap.put("/v1/login/update","perms[user:update]");


        filterMap.put("/**","authc");

        shiroFilterFactoryBean.setLoginUrl("/v1/login/tologin");

        shiroFilterFactoryBean.setUnauthorizedUrl("/v1/login/unAuth");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return shiroFilterFactoryBean;
    }



    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean(name="defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);

        return  defaultWebSecurityManager;
    }



    @Bean(name="userRealm")
    public UserRealm getUserRealm(){
        return new UserRealm();
    }



    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }


}

